<?php
namespace Home\Controller;
use Common\Controller\CommonController;
use Home\Controller\SourceController;
class SaleController extends CommonController {
	public function _initialize(){

		parent::_initialize();
	}
	/**
	 * 订售首页
	 */
	public function index(){
		$list=M('Sale_config')->select();
		foreach ($list as $k=>$v){
			$list[$k]['money']=floatval($v['money']);
			$list[$k]['rate']=floatval($v['rate']);
		}
		$data['point_config']=$list;
		$data['currency_list']=M('Currency')->where('is_line = 1')->select();
		$data['msg']=M('Message_all')->order('add_time')->find();
		$this->ajaxReturn($data,'JSONP');
	
	}
	
	/**
	 * 添加订售订单
	 */
	public function addSale(){
		$a=$this->checkTime(I('currency_id'));
		if(!$a){
			$arr['status']=0;
			$arr['info']='交易未开启，请在交易时间内进行交易';
			$this->ajaxReturn($arr,'JSONP');
		}
// 		if(empty($_SESSION['is_pwd'])){
// 			$arr['status']=0;
// 			$arr['info']='交易密码过期，请重新输入';
// 			$this->ajaxReturn($arr,'JSONP');
// 		}
		$member=M('Member')->where('member_id ='.$_SESSION['member_id'])->find();
		if($member['rmb']<I('money')){
			$arr['status']=0;
			$arr['info']='账户余额不足';
			$this->ajaxReturn($arr,'JSONP');
		}
		$data['order_num']=$_SESSION['member_id'].time();
		$data['member_id']=$_SESSION['member_id'];
		$data['currency_id']=I('currency_id');
		$data['buy_point']=I('buy_point');
		$data['money']=I('money');
		$data['sale_type']=I('sale_type');
		$data['type']=I('type');
		$data['rise_percent']=I('rise_percent');
		$data['fall_percent']=I('fall_percent');  
		$data['add_time']=time();
		$data['status']=0;
		$data['rise_money']=I('money')*(1+I('rise_percent')/100);
		$data['fall_money']=I('money')*(1-I('fall_percent')/100);
		$r[]=M('Sale_orders')->add($data);
		$r[]=M('Member')->where('member_id ='.$_SESSION['member_id'])->setDec('rmb',I('money'));		
		if(in_array(false, $r)){
			$arr['status']=0;
			$arr['info']='操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}
	}
	
	/**
	 * 手动平仓订售订单
	 */
	public function balance_one(){
		$sale_id=I('id');
		if(M('Sale_orders')->where('id ='.$sale_id)->find()['status']==1){
			$arr['status']=0;
			$arr['info']='已平仓，请不要重复操作';
			$this->ajaxReturn($arr,'JSONP');
		}
		$r=$this->balance($sale_id);
		if($r){
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=0;
			$arr['info']='操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}
		
	}
	
	/**
	 * 一键平仓
	 */
	public function balance_all(){
		$sale_list=M('Sale_orders')->where('member_id ='.$_SESSION['member_id'])->select();
		foreach ($sale_list as $k=>$v){
			$r[]=$this->balance($v['id']);
		}
		if(in_array(false, $r)){
			$arr['status']=0;
			$arr['info']='操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}
	}
	private function random(){
		$time=time();
		$timen=substr($time, -2);
		$minute=date('i',$time);
		$second=date('s',$time);
		$num=round(($timen+$minute+$second)/300,2);
		if($timen%2==0){
			$num=0-$num;
		}
		return $num;
	}
	/**
	 * 结算订售单
	 */
	
	private function balance($sale_id){
		$fee=M('Config')->where(['key' => 'day_fee'])->find()['value'];
		$SOURCE=new SourceController();
		$sale=M('Sale_orders')->where('id ='.$sale_id)->find();
		$a=$this->checkTime($sale['currency_id']);
		if(!$a){
			return false;
		}
		$random=$this->random();
		$lever=M('Currency')->where('currency_id ='.$sale['currency_id'])->find()['lever'];
		$result=$SOURCE->result($sale['currency_id']);
		$new_price=$result->Price*$lever+$random;
		$rate=M('Sale_config')->where('id ='.$sale['sale_type'])->find()['rate'];
		
		if($sale['type']==1){
			//修改订单状态
			$profit=($new_price-$sale['buy_point'])/$rate;
			$arr['trade_time']=time();
			$arr['status']=1;
			$arr['profit']=$profit;
			//添加平仓金钱
			$r[]=M('Member')->where('member_id ='.$_SESSION['member_id'])->setInc('rmb',$profit);
			//计算隔夜费
			$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
			$daynum=$this->checkDay($sale_orders['add_time'], time());
			$fee_all=$sale['money']*$daynum*$fee;
			if($fee_all!=0){
			$r[]=M('Member')->where('member_id ='.$_SESSION['member_id'])->setDec('rmb',$fee_all);
			}
			$arr['fee']=$fee_all;
			//修改订单状态
			$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
			if(in_array(false, $r)){
					return false;
				}else{
					return true;
				}
		}
		if($sale['type']==2){
				$profit=($sale['buy_point']-$new_price)/$rate;
				$arr['trade_time']=time();
				$arr['status']=1;
				$arr['profit']=$profit;
				//添加平仓金钱
				$r[]=M('Member')->where('member_id ='.$_SESSION['member_id'])->setInc('rmb',$profit);
				//计算隔夜费
				$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
				$daynum=$this->checkDay($sale_orders['add_time'], time());
				$fee_all=$sale['money']*$daynum*$fee;
				$r[]=M('Member')->where('member_id ='.$_SESSION['member_id'])->setDec('rmb',$fee_all);
				$arr['fee']=$fee_all;
				//修改订单状态
				$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
				if(in_array(false, $r)){
					return false;
				}else{
					return true;
				}
			}
	}
	/**
	 * 判断隔夜天数
	 */
	private  function checkDay($startTime,$endTime){		
			$times=0;
			$starthour=date('H',$startTime);
			$end_four = date('H',$endTime);
			$time=strtotime("today 04:00:00");
			if($starthour<4){
				$time=strtotime("today 04:00:00");
				for($i=0;$i<10000;$i++){
					if($endTime>$time+$i*3600*24){
						$times=$i;
					}else{
						break;
					}
				}
			}
			else{
				$time=strtotime("+1day 04:00:00");
				for($i=0;$i<10000;$i++){
					if($endTime>$time+$i*3600*24){
						$times=$i;
					}else{
						break;
					}
				}
			}
			return $times;
		}


	/**
	 * 订售记录查询
	 */
	public function record(){
		$SOURCE=new SourceController();
		$rmb=M('Member')->where('member_id ='.$_SESSION['member_id'])->find()['rmb'];
		$data['rmb']=$rmb;
		$where1['member_id']=$_SESSION['member_id'];
		$where1['add_time']=['BETWEEN',[strtotime(date( "Y-m-d", time())),time()]];
		$sale_count_day=M('Sale_orders')->where($where1)->sum('profit');
		$sale_count_all=M('Sale_orders')->where('member_id ='.$_SESSION['member_id'])->sum('profit');
		$data['sale_count_all']=$sale_count_all;
		$data['sale_count_day']=$sale_count_day;
		if(!empty(I('type'))){
			$where['type']=I('type');
		}
		if(!empty(I('status'))){
			$where['status']=I('status');
		}
		$where['member_id']=$_SESSION['member_id'];
		$list=M('Sale_orders')->where($where)->select();
		$profit_all=0;
		if(!$list){
			$data['list']='';
			$data['status']=0;
			$this->ajaxReturn($data,'JSONP');
		}else{
			foreach ($list as $k=>$v){
				$currency=M('Currency')->where('currency_id ='.$v['currency_id'])->find();
				$list[$k]['currency_name']=$currency['currency_name'];
				$sale_config=M('Sale_config')->where('id = '.$v['sale_type'])->find();
				$list[$k]['sale_name']=$sale_config['name']."(".$sale_config['money']."元/手)";
				$result=$SOURCE->result($v['currency_id']);
				$now_price=$result->Price*$currency['lever'];
				$list[$k]['now_price']=$now_price;
				$list[$k]['money']=floatval($v['money']);
				$profit_all+=$v['money']+$v['profit'];
				if($v['status']==0){
					if($v['type']==1){
						$list[$k]['profit']=floatval(round(($now_price-$v['buy_point'])/$sale_config['rate'],2));
						$profit_all+=($now_price-$v['buy_point'])/$sale_config['rate'];
					}
					if($v['type']==2){
						$list[$k]['profit']=floatval(round(($v['buy_point']-$now_price)/$sale_config['rate'],2));
						$profit_all+=($v['buy_point']-$now_price)/$sale_config['rate'];
					}
					}else{
						$list[$k]['profit']=floatval($v['profit']);
					}
			}
			$data['profit_all']=round($profit_all,2);
			$data['list']=$list;
			$data['status']=1;
			$this->ajaxReturn($data,'JSONP');
		}
	}
	
	/** 
	 * 检测交易时间
	 */
	private function checkTime($currency_id){
		$currency=M('Currency')->where('currency_id ='.$currency_id)->find();
		$time=strtotime(date('Y-m-d'));
		$start_time=$time+$currency['start_time_h']*3600+$currency['start_time_m']*60;
		$over_time=$time+$currency['end_time_h']*3600+$currency['end_time_m']*60;
		$start_x_time=$time+$currency['start_time_x_h']*3600+$currency['start_time_x_m']*60;
		$over_x_time=$time+$currency['end_time_x_h']*3600+$currency['end_time_x_m']*60;
		if((time()<$start_time||time()>$over_time)  &&  (time()<$start_x_time||time()>$over_x_time)){
			return false;
		}
		$week = date("l"
				,time());  //获取当前日期是周几
		if($week == 'Saturday' && $currency['is_lock_6'] == 1){
			return false;
		}
		if($week == 'Sunday' && $currency['is_lock_7'] == 1 ){
			return false;
		}
		return true;
	}
}